<template>
  <UploadExcel :on-success="handleSuccess" />
</template>

<script>
import { reqImportEmployee } from '@/api/employees'
// const userRelations = {
//   '入职日期': 'timeOfEntry',
//   '手机号': 'mobile',
//   '姓名': 'username',
//   '转正日期': 'correctionTime',
//   '工号': 'workNumber'
// }
export default {
  name: 'Import',
  computed: {
    type() {
      return this.$route.query.type
    }
  },
  methods: {
    handleSuccess({ header, results }) {
      if (this.type === 'user') {
        this.handleAddEmployee({ header, results })
      }
      if (this.type === 'money') {
        this.$message.error('导入失败')
      }
    },
    async handleAddEmployee({ header, results }) {
      const userRelations = {
        入职日期: 'timeOfEntry',
        手机号: 'mobile',
        姓名: 'username',
        转正日期: 'correctionTime',
        工号: 'workNumber'
      }
      const arr = []
      results.forEach((item) => {
        const obj = {}
        for (const key in item) {
          const newArr = userRelations[key]
          if (newArr === 'timeOfEntry' || newArr === 'correctionTime') {
            obj[newArr] = this.formatExcelDate(item[key], '-')
          } else {
            obj[newArr] = item[key]
          }
        }
        console.log(obj)
        arr.push(obj)
      })
      await reqImportEmployee(arr)
      this.$router.push('/employees')
      this.$message.success('批量导入成功')
    },
    formatExcelDate(numb, format) {
      const time = new Date((numb - 1) * 24 * 3600000 + 1)
      time.setYear(time.getFullYear() - 70)
      const year = time.getFullYear() + ''
      const month = time.getMonth() + 1 + ''
      const date = time.getDate() - 1 + ''
      if (format && format.length === 1) {
        return (
          year +
          format +
          (month < 10 ? '0' + month : month) +
          format +
          (date < 10 ? '0' + date : date)
        )
      }
      return (
        year +
        (month < 10 ? '0' + month : month) +
        (date < 10 ? '0' + date : date)
      )
    }
  }
}
</script>

<style></style>
